package client;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Scanner;

import util.CmdParse;

public class Client {
	public void start() throws IOException{
		
		
		Socket socket=new Socket("127.0.0.1",9999);
		OutputStream out=socket.getOutputStream();
		InputStream in=socket.getInputStream();
		BufferedReader reader=new BufferedReader(new InputStreamReader(in));
		
		Scanner scanner=new Scanner(System.in);
		String tip=null;
		String command = null;
		
		while(!"200OK".equals(tip=reader.readLine())){
			System.out.println(tip);
			command = scanner.nextLine()+"\n";
			out.write(command.getBytes());
		}
//		System.out.println("tiaoshi"+command);
		
		if(CmdParse.parseCmd(command)[0].equals("LS")){
			while(!"end".equals(tip=reader.readLine())){
				System.out.println(tip);
			}
		}else if (CmdParse.parseCmd(command)[0].equals("rm")){
			tip=reader.readLine();
			System.out.println(tip);
		}else{
			String file = CmdParse.parseCmd(command)[1];
			
			InputStream fin = new FileInputStream(file);
			byte[] buf = new byte[fin.available()];
			fin.read(buf);
			out.write(buf);
			fin.close();
			out.write("finished\n".getBytes());
		}
				
		scanner.close();
		in.close();
		out.close();
		socket.close();
		
		
	}
	
	public static void main(String[] args) throws IOException {
		new Client().start();
	}

}
